<?php
/**
 * Holds class Enum
 *
 * @author daantimmer
 *
 * @package Library
 * @subpackage Enum
 */

/**
 * Basic class for creating Enumerated types
 *
 * @author daantimmer
 */
class Enum {
	protected $selfValue = array("key"=>null,"value"=>null);
	protected $self = array ( );
	protected $index = array ();
	
	private $indexValue = 0;
	
	/**
	 * Constructor
	 *
	 * Takes an arbitrary amount of params. Each param should be a string.
	 * Each param will get a unique identifier starting at 0. Each next enum will increment by 1
	 *
	 * @return void
	 */
	public function __construct( /*...*/ ) {
		$args = func_get_args ();
		for($i = 0, $n = count ( $args ); $i < $n; $i ++)
			$this->{$args[$i]} = null;
			//$this->add ( $args [$i] );
	}
	
	public function getAll() {
		return $this->self;
	}
	
	public function __get( /*mixed*/ $var = null) {
		if($var == "self")
			return $this->selfValue;
		return $this->self [$var];
	}
	
	public function __set($var, $value){
		if( "self" == $var)
			$this->set($value);
		else
			$this->add($var, $value);
	}
	
	public function getKey(/*mixed*/ $var){
		if(is_numeric($var-1))
			return $this->index[$var]["key"];
		return null;
	}
	
	public function getValue(/*mixed*/ $var){
		if(is_numeric($var))
			return $this->index[$var]["value"];
		return null;
	}
	
	public function get(/*int*/ $index) {
		return $this->index[$index];
	}
	
	public function set(/*string*/ $naam){
		$this->selfValue = $this->get($this->$naam);
	}
	
	function __toString(){
		return "[".$this->selfValue["key"]."] = ".$this->selfValue["value"];
	}
	
	public function add( /*string*/ $name = null, /*int*/ $enum = null) {
		if (isset ( $enum ))
			$this->self [$name] = $enum;
		else
			$this->self [$name] = $this->indexValue++;
		
		$this->index[$this->self [$name]] = array("key" => $name,"value" => $this->self[$name]);
	}
	
	public function isBitset($value,$bit){
		$cp = $value&$bit;
		return empty($cp)?0:1;
	}
	
	public function getJsonAssoc(){
		$json = array();
		foreach($this->self as $key => $val){
			$json[$key] = $key;
		}
		return json_encode($json);
	}
	
	public function getJsonKeyed(){
		$json = array();
		foreach($this->self as $key => $val){
			$json[$val] = $key;
		}
		return json_encode($json);
	}
}